﻿<?php

# Supress notice
@session_start();

require 'conf.php';

function base64url_encode($data) { 
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
} 

function changepic($sessiontoken, $imgdata){
    global $MW_host;
    $fields = array('USR_SET_PICTURE' => '',
                    'SESSION' => $sessiontoken,
                    'IMAGE' => $imgdata);

    $fields = http_build_query($fields);

    $h = curl_init($MW_host);
    curl_setopt($h, CURLOPT_POST, 1);
    curl_setopt($h, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($h, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
    
    $res = curl_exec($h);
    
    if(!mb_check_encoding($res, 'UTF-8'))
        $res = utf8_encode($res);
    $data = json_decode($res);
    return $data;
}

function redirect_successful() 
{
    echo "<html><head><script>window.location = '/';</script></head></html>";
}

function redirect_with_message($msg)
{
    echo "<html><head><meta charset='utf-8'><script>alert('$msg'); window.location = '/';</script></head></html>";
}

set_time_limit(120);

if (!isset($_SESSION['sessiontoken'])) {
    redirect_with_message('Var god logga in igen');
    exit();
} else if ($_FILES["uploadedfile"]["error"] > 0) {
    echo $_FILES["uploadedfile"]["error"];
    exit();
} else if (!isset($_FILES['uploadedfile']['tmp_name'])) {
    redirect_with_message("Ingen fil angiven");
    exit();
} else {
    $data = file_get_contents($_FILES['uploadedfile']['tmp_name']);
    
    $d = base64url_encode($data);
    
    $res = changepic($_SESSION['sessiontoken'], $d);
    if ($res === null) {
        redirect_with_message("Ett fel uppstod i komunikationen med mellan-servern");
    } else if (isset($res->error)) {
        redirect_with_message($res->error);
    } else {
        redirect_successful();
    }
}

?>
